package com.arm.controller.admin.user;

import com.arm.controller.BaseController;
import com.arm.def.Constant;
import com.arm.def.MessageConstant;
import com.arm.module.AdminMenu;
import com.arm.module.AdminUser;
import com.arm.module.Role;
import com.arm.service.AdminUserService;
import com.arm.service.MenuService;
import com.arm.service.RoleService;
import com.arm.tools.MD5Tools;
import com.arm.tools.ToolsBase;
import com.arm.tools.ValidateCode;
import com.arm.tools.myRunTime.MyRunTimeExcption;
import com.arm.tools.result.ResultObj;
import com.arm.tools.result.ReturnCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Andrew  on 2017/2/26.
 */
@RestController
@RequestMapping(value = "/admin/user")
public class AdminUserController extends BaseController {
    /*@Autowired
    RedisCache redisCache;*/
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    AdminUserService adminUserService;


    @RequestMapping(value = "/gotoLogin")
    public ModelAndView gotoLogin(HttpServletRequest request) {
        ModelAndView mov = new ModelAndView();
        mov.setViewName("admin/user/login");

        return mov;

    }


    /**
     * 获取验证码
     */
    @GetMapping(value = "/getVerificatioCode")
    public void getVerificationCode(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("====================getVerificatioCode======================================================================================");
        response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        ValidateCode vCode = new ValidateCode(160, 40, 5, 150);
        try {
            String key = Constant.SESSION_KEY_RANDOM_VALIDATE_CODE;
            super.session.setAttribute(key, vCode.getCode());
            logger.info("随机验证码：" + vCode.getCode());
            vCode.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/Login", method = RequestMethod.POST)
    @ResponseBody
    public String Login(HttpServletRequest request) {
        //applicationContext.

        ResultObj resultObj = new ResultObj();
        try {
            Map<String, String> map = this.showRequestParameters(request);
            String randomCode = (String) request.getSession().getAttribute(Constant.SESSION_KEY_RANDOM_VALIDATE_CODE);
            String code = map.get("code");
            if(StringUtils.isBlank(code)){
                throw new MyRunTimeExcption("code is null");
            }
            if (!code.toLowerCase().equals(randomCode.toLowerCase())) {
                logger.info(code + "<<<randomCode>>>" + randomCode);
                throw new MyRunTimeExcption(MessageConstant.CODE_ERRO);
            }
            AdminUser adminUser = adminUserService.login(this.showRequestParameters(request));
            if (adminUser == null) {
                throw new MyRunTimeExcption(MessageConstant.USERNAME_PASSWORD_ERRO);
            }
            request.getSession().setAttribute(Constant.SESSION_KEY_ADMIN_USER_LOGIN, adminUser);


            resultObj.setMsg(MessageConstant.LOGIN);
        } catch (MyRunTimeExcption myRunTimeExcption) {
            myRunTimeExcption.printStackTrace();
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(myRunTimeExcption.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(e.getMessage());
        }

        return resultObj.toJson();

    }

    /**
     * 跳转到修改页面
     *
     * @param request
     * @param tid
     * @return
     */
    @RequestMapping(value = "/updatePassWord")
    @ResponseBody
    public ModelAndView updatePassWord() {
        ModelAndView mov = new ModelAndView();
        mov.setViewName("admin/user/updatePassWord");
        return mov;
    }

    /**
     * 用户列表
     *
     * @param request
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/getUserList")
    public ModelAndView getUserList(HttpServletRequest request, Integer page, Integer pageSize) {
        ModelAndView mov = new ModelAndView();
        mov.setViewName("admin/user/userList");

        if (page == null || page == 0) {
            page = Constant.PAGENUM;
        }
        // 设置每页记录数
        if (pageSize == null || pageSize == 0) {
            pageSize = Constant.PAGESIZENum;
        }
        PageHelper.startPage(page, pageSize);
        Map<String, String> map = this.showRequestParameters(request);
        List<AdminUser> userList = adminUserService.getUserList(map);

        PageInfo<AdminUser> pageinfo = new PageInfo<AdminUser>(userList);
        mov.addObject("pageinfo", pageinfo);
        mov.addObject("bean", map);
        return mov;

    }

    @RequestMapping(value = "/getUser")
    public ModelAndView getUser(Long tid) {
        ModelAndView mov = new ModelAndView();
        mov.setViewName("admin/user/adminUserAdd");
        List<Role> roleList = roleService.getRoleList(null);
        mov.addObject("roleList", roleList);
        try {
            if (tid != null) {
                AdminUser adminUser = adminUserService.getUser(new HashMap<String, String>() {
                    {
                        put("tid", String.valueOf(tid));
                    }
                });
                mov.addObject("adminUser", adminUser);

            }

        } catch (MyRunTimeExcption e) {
            e.printStackTrace();
        }
        return mov;

    }

    /**
     * 修改后台用户信息
     *
     * @return
     */
    @RequestMapping(value = "/modifyUser", method = RequestMethod.POST)
    @ResponseBody
    public String modifyUser(AdminUser adminUser) {

        ResultObj resultObj = new ResultObj();
        try {
            adminUserService.modifyUser(adminUser);
            resultObj.setMsg("成功！");
        } catch (MyRunTimeExcption myRunTimeExcption) {
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(myRunTimeExcption.getMessage());
            myRunTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return resultObj.toJson();
    }

    /**
     * 修改密码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
    @ResponseBody
    public String modifyPassword(String oldPassWord, String passWord) {

        ResultObj resultObj = new ResultObj();
        try {


            AdminUser adminUser = (AdminUser) super.session.getAttribute(Constant.SESSION_KEY_ADMIN_USER_LOGIN);
            if (adminUser == null) {
                throw new MyRunTimeExcption(MessageConstant.USER_INEXISTENCE);
            }
            String pageOldPassWord = MD5Tools.MD5(oldPassWord);

            if (!pageOldPassWord.equals(adminUser.getPassWord())) {
                logger.info(pageOldPassWord + "===>>>" + adminUser.getPassWord());
                throw new MyRunTimeExcption(MessageConstant.PASSWORD_ERRO);
            }
            adminUser.setPassWord(MD5Tools.MD5(passWord));
            adminUserService.modifyUser(adminUser);
            resultObj.setMsg(MessageConstant.MODIFY_PASSWORD_SUCCESS);

        } catch (MyRunTimeExcption myRunTimeExcption) {
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(myRunTimeExcption.getMessage());
            myRunTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }

        return resultObj.toJson();

    }

    /**
     * 重置密码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/resetPassword")
    @ResponseBody
    public String resetPassword(Long tid) {
        System.out.println("=================================resetPassword==========================================>>>>>>");

        ResultObj resultObj = new ResultObj();
        try {
            AdminUser adminUser = adminUserService.selectAdminById(new HashMap<String, String>() {{
                put("tid", String.valueOf(tid));
            }});
            if (adminUser == null) {
                throw new MyRunTimeExcption(MessageConstant.USER_INEXISTENCE);
            }
            adminUser.setPassWord(MD5Tools.MD5("123456"));
            adminUserService.modifyUser(adminUser);
            resultObj.setMsg(MessageConstant.PASSWORD_RESET_SUCCESS);
        } catch (MyRunTimeExcption myRunTimeExcption) {
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(myRunTimeExcption.getMessage());
            myRunTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }

        return resultObj.toJson();

    }

    @RequestMapping(value = "/loginOut", method = RequestMethod.POST)
    @ResponseBody
    public String loginOut(HttpServletRequest request) {
        System.out.println("===============================loginOut============================================>>>>>>");

        ResultObj resultObj = new ResultObj();
        try {
            request.getSession().invalidate();
        } catch (MyRunTimeExcption myRunTimeExcption) {
            myRunTimeExcption.printStackTrace();
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(myRunTimeExcption.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(e.getMessage());
        }
        return resultObj.toJson();
    }
}
